<template>
	<view>
		<cl-navbar :title="$t('my.index.inviteRewards')" leftIconSize="40rpx" placeholder autoBack>
		</cl-navbar>
		<view class=" p-2 mb-3 contentBox">
			<view class="star-bg p-2 rounded">
				<!-- 我的邀请码 -->
				<text class="font28 color333">{{$t('invite.title')}}</text>
				<view class="py-2 flex">
					<view class="pr-2">
						<text class="font46 color333">{{codeData.invite_code}}</text>
					</view>
					<!-- <view class="pr-2" v-else="codeData.invite_up">
						<text class="font46 colorF">xxx</text>
					</view> -->
					<view class="flex align-center pt-1" v-if="codeData.invite_up">
						<u-icon name="file-text" color="#cccccc" size="22" @click="copyText"></u-icon>
					</view>
				</view>
				<view class="rounded p-2 rounded" style="background-color: rgba(200, 200, 200, .1);"
					v-if="codeData.invite_up">
					<!-- 上级邀请码 -->
					<text class="font30 color333">{{$t('invite.upCode')}}：{{codeData.invite_up}}</text>
				</view>
				<view class="" v-else>
					<u-button :text="$t('invite.inputUpCode')"
						color="linear-gradient(to right, #ff5b7a, #ff7a3d)" @click="open"></u-button>
				</view>
			</view>
			<view class="star-bg p-2 rounded mt-2 grid-col2">
				<view class="flex flex-column align-center">
					<text class="color333 font36">{{teamTotal.one}}</text>
					<!-- 直推人数 -->
					<text class="colorC font30 pb-1">{{$t('invite.DirectPush')}}</text>
				</view>
				<view class="flex flex-column align-center">
					<text class="color333 font36">{{teamTotal.two}}</text>
					<!-- 间推人数 -->
					<text class="colorC font30 pb-1">{{$t('invite.InterPush')}}</text>
				</view>
			</view>
			<view class="pt-3">
				<view class="">
					<!-- 邀请奖励规则 -->
					<text class="colorA font32">{{$t('invite.rule')}}</text>
				</view>
				<view class=" pt-3" v-for="(item,index) in ruleList" :key="index">
					<text class="color9 font32">{{index+1}}、</text>
					<text class="color9 font32">{{item.text}}</text>
				</view>
			</view>
			<view class="position-fixed bottom-0 left-0 right-0 safe-bottom px-2 flex"
				style="z-index: 9999;">
				<view class="p-2 flex-1">
					<u-button :text="$t('invite.saveUrl')" type="success" @click="copyLink"></u-button>
				</view>
				<view class="p-2 flex-1">
					<u-button :text="$t('invite.savePic')" type="primary" :disabled="qrcodeUrl==''"
						@click="posterOpen"></u-button>
				</view>
			</view>
			<!-- 邀请海报 -->
			<u-popup :show="posterShow" @close="posterClose" @open="posterOpen" mode="center" :round="10"
				:closeOnClickOverlay="true" bgColor="rgba(0,0,0,0)">
				<view class="">
					<view class="colorF flex flex-column justify-center align-start position-relative"
						style="background-color: none;">
						<u--image :showLoading="true" :src="posterImg" :width="cw+'px'" :height="ch+'px'"
							mode="scaleToFill"></u--image>
						<!-- <canvas canvas-id="posterCanvas" id="posterCanvas"
							:style="{ height: ch+'px', width: cw+'px'}"></canvas> -->
						<view class="p-2 position-absolute top-0 right-0">
							<u-icon size="22" name="close-circle" color="#ffffff" @click="posterClose()"></u-icon>
						</view>
					</view>
					<view class="p-2 flex justify-center align-center">
						<u-icon :label="$t('invite.savePhone')" size="22" name="download" color="#ffffff"
							labelColor="#ffffff" @click="savePoster"></u-icon>
					</view>
				</view>

			</u-popup>
			<!-- 填写邀请码 -->
			<u-popup :show="show" @close="close" @open="open" mode="center" :round="10" :closeOnClickOverlay="false">
				<view style="width: 80vw;" class="p-3">
					<view class="">
						<text class="color333  font32 py-2">{{$t('invite.inputUpCode')}}</text>
					</view>
					<view class="py-4">
						<input class="uni-input px-3 border py-3 rounded-circle color0 font32" focus
							:placeholder="$t('invite.inputUpCode')" v-model="codeValue" />
					</view>
					<view class="grid-col2 grid-space10">
						<view class="">
							<u-button :text="$t('common.cancelText')" shape="circle" @click="close()"></u-button>
						</view>
						<view class="">
							<u-button :text="$t('recommend.modalConfirm')" shape="circle"
								color="linear-gradient(to right, #ff5b7a, #ff7a3d)"
								@click="bindUpUser"></u-button>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
		<view class="overflow-hidden" style="height: 0px;width: 0px;">
			<canvas canvas-id="qrcode" style="width: 180px; height: 180px;"></canvas>
			<canvas canvas-id="posterCanvas" id="posterCanvas" style="width: 500px; height: 938px;"></canvas>
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import uQrcode from '@/common/uqrcode.js'
	export default {
		data() {
			return {
				cw: uni.$u.sys().windowWidth - 60,
				ch: (uni.$u.sys().windowWidth - 60) * 1.9,
				bgColor: "#ededed",
				show: false,
				posterShow: false,
				codeData: {},
				teamTotal: {
					one: '',
					two: ''
				},
				codeValue: '',
				oneLevel: [],
				twoLevel: [],
				formData: {
					type: '',
					page: 1,
					limit: 10,
					nick_name: ''
				},
				ruleList: [],
				myLink: '',
				textShow: '已复制邀请链接，去分享给好友吧！',
				proportion: 1.9, //高除以宽 19/10 1520/800
				qrcodeUrl: '', //二维码
				posterBg: '/static/playlet/posterBG.jpg',
				posterImg: '',
				disH: 0.50,
				disW: 0.28,
				showDown: false
			};
		},
		onShow() {
			this.getMycode()
			this.getInvitText()
			this.getMyLower(1);
			this.getMyLower(2);

			// let isimg=uni.getStorageSync("csdocPoster")
			// if(isimg){
			// 	console.log('onShowonShow',isimg);
			// 	this.posterImg=isimg
			// }
		},
		mounted() {
			this.getUserUrl()
			// setTimeout(()=>{

			// 	// this.getSharePoster()
			// },2000)
		},
		computed: {
			...mapState({
				user_info: state => state.user.user_info,
			}),
		},
		methods: {
			getSharePoster() {

				uni.showLoading({
					title: 'loading...'
				});
				let that = this;
				var ctx = uni.createCanvasContext('posterCanvas');
				var canvasW = 800;
				var canvasH = 1520;
				let bgimg = this.posterBg
				let qrcodeImg = this.qrcodeUrl
				ctx.drawImage(bgimg, 0, 0, this.cw, this.ch)
				ctx.drawImage(qrcodeImg, this.cw * this.disW, this.ch * this.disH, this.cw * 0.44, this.cw * 0.44)
				ctx.setFontSize(18);
				ctx.setFillStyle('black');
				ctx.fillText('@' + that.user_info.nick_name, 10, 500, 300)
				setTimeout(() => {
					ctx.draw(false, () => {
						setTimeout(() => {
							that.showDown = true;
						}, 100)
						uni.hideLoading()
					})
					// uni.canvasToTempFilePath({
					//     canvasId: 'posterCanvas',
					//     success: (res) => {
					//          this.posterImg = res.tempFilePath
					//     },
					// })
				}, 1000)
			},
			// 邀请码生成二维码
			getQrcodeImg(url) {
				uQrcode.make({
					canvasId: 'qrcode',
					text: url,
					size: 160,
					margin: 10,
					backgroundColor: '#ffffff',
					foregroundColor: '#000000',
					fileType: 'jpg',
					success: res => {
						console.log("邀请码生成二维码", res);
						this.qrcodeUrl = res
						this.makePoster(res)
					},
					complete: () => {
						// uni.hideLoading()
					}
				})
			},
			// 制作海报
			makePoster(isurl) {
				let that = this;
				console.log("点击getSharePoster", this.user_info.nick_name);
				var ctx = uni.createCanvasContext('posterCanvas');
				let bgimg = '/static/playlet/posterBG.jpg'
				ctx.drawImage(bgimg, 0, 0, 500, 938)
				ctx.drawImage(isurl, 150, 477, 200, 200)
				ctx.setFontSize(26);
				ctx.setFillStyle('white');
				// ctx.fillText('@' + that.user_info.nick_name, 10, 500, 300)
				// 获取文本宽度
				let text=""
				if(that.user_info.nick_name){
					text = '@' + that.user_info.nick_name;
				}else{
					text = 'SKY APP';
				}
				const textWidth = ctx.measureText(text).width;
				// 计算居中的 x 坐标
				const centerX = (500 - textWidth) / 2;
				// 绘制文本
				ctx.fillText(text, centerX, 760);
				setTimeout(() => {
					ctx.draw(false, () => {
						uni.canvasToTempFilePath({
							canvasId: 'posterCanvas',
							success: (res) => {
								// this.posterImg = res.tempFilePath
								uni.saveFile({
									tempFilePath: res.tempFilePath,
									success: function(res) {
										let savedFilePath = res.savedFilePath;
										console.log("保存本地海报", res.savedFilePath);
										that.posterImg = savedFilePath;
										uni.setStorageSync("docPoster",
											savedFilePath)
									},
									fail: function(error) {
										console.log('保存文件失败', error);
									}
								});
							},
						})
					})

				}, 1000)
			},
			// 保存海报
			savePoster() {
				let that = this
				uni.saveImageToPhotosAlbum({
					filePath: that.posterImg,
					success(re) {
						uni.showToast({
							title: '保存成功',
							icon: 'none'
						});
						that.posterClose()
					},
					fail(err) {
						console.log(err);
						uni.showToast({
							title: '保存失败',
							icon: 'none'
						});
					}
				});
			},
			posterClose() {
				this.posterShow = false
				this.showDown = false
			},
			posterOpen() {
				this.posterShow = true
				// this.getSharePoster()
			},
			close() {
				this.codeValue = '';
				this.show = false;
			},
			open() {
				this.show = true;
			},
			btnClick() {
				uni.setClipboardData({
					data: this.myLink,
					success: function() {
						uni.showToast({
							title: '已复制邀请链接，去分享给好友吧！',
							icon: 'none',
							duration: 2000
						});
					},
					fail: function(err) {
						this.posterShow = true
					}
				});
			},
			bindUpUser() {
				this.$api.playlet.bindUpUser({
					code: this.codeValue
				}).then(res => {
					console.log("我的邀请码", res);
					if (res.code == 200) {
						this.close()
						this.getMycode()
					}
				})
			},
			// 获取我的推广链接
			getUserUrl() {
				this.$api.playlet.getUserUrl().then(res => {
					console.log('获取我的推广链接', res);
					this.myLink = res.data.url
					this.getQrcodeImg(res.data.url)
				})
			},
			// 获取邀请奖励规则
			getInvitText() {
				this.$api.playlet.getRewardNote().then(res => {
					console.log('获取邀请奖励规则', res);
					this.ruleList = res.data
				})
			},
			getMycode() {
				this.$api.playlet.getMycode().then(res => {
					console.log("我的邀请码", res);
					this.codeData = res.data
					this.oneLevel = [];
					this.twoLevel = [];
					this.getMyLower(1);
					this.getMyLower(2);
				})
			},
			getMyLower(type) {
				let formData = {
					type: type,
					page: 1,
					limit: 3
				}
				this.$api.playlet.getMyLower(formData).then(res => {
					console.log("我的下级", res);
					if (type == 1) {
						this.oneLevel = res.data.list
						this.teamTotal = res.data.total
					} else if (type == 2) {
						this.twoLevel = res.data.list
					}
				})
			},
			copyLink() {
				if (this.myLink) {
					const textToCopy = this.myLink
					// 设置剪贴板的内容
					uni.setClipboardData({
						data: textToCopy,
						success: function() {
							uni.showToast({
								title: '复制成功',
								icon: 'none',
								duration: 2000
							});
						},
						fail: function(err) {
							uni.showToast({
								title: '复制失败',
								icon: 'none',
								duration: 2000
							});
						}
					});
				} else {
					uni.showToast({
						title: '您还没有邀请码',
						icon: 'none',
						duration: 2000
					});
				}

			},
			copyText() {
				if (this.codeData.invite_code) {
					const textToCopy = this.codeData.invite_code;
					// 设置剪贴板的内容
					uni.setClipboardData({
						data: textToCopy,
						success: function() {
							uni.showToast({
								title: '复制成功',
								icon: 'none',
								duration: 2000
							});
						},
						fail: function(err) {
							uni.showToast({
								title: '复制失败',
								icon: 'none',
								duration: 2000
							});
						}
					});
				} else {
					uni.showToast({
						title: '您还没有邀请码',
						icon: 'none',
						duration: 2000
					});
				}

			},
			leftClick() {
				uni.switchTab({
					url: "/pages/user/index"
				})
			}
		}
	}
</script>

<style lang="scss">

</style>